package com.friend.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;


public class ProxyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// This is used to fetch remote data for ajax calls.  ick.

		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		client.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

		String responseXml = "<b>no URL specified in path_info</b>";
		HttpMethod get = null;

		try {
			String url = request.getPathInfo();
			String host = request.getServerName() + ":" + Integer.toString(request.getServerPort());
			// Apache strips double slashes and replaces them with single slashes
			if (!url.contains("http://")) {
				url = url.replace("http:/", "http://");
			}
			responseXml = "<b>Trying to fetch " + url.substring(1) + "</b>";
			get = new GetMethod(url.substring(1));
			int responseCode = client.executeMethod(get);
			
			// TODO: Lou 06/01/06: Real test for success requires checking for some specific string in the response -- the return code is always 200 unless the page is down
			responseXml = get.getResponseBodyAsString();
			
			// Need to validate XML here....

			
			String opensocial_re = "<Require\\s*feature=\"opensocial-0.5\"\\s*/>";
			// FIXME - for some reason .matches(opensocial_re) never matches here... odd
			if (responseXml.contains("opensocial-0.5")) {
		    	responseXml = responseXml.replaceFirst(opensocial_re, "<!-- replaced by hi5 module proxy -->");
		    	String jscode = 
		    		"$1<script src=\"http://" + host + "/friend/gadgets/script/jquery.js\" type=\"text/javascript\"></script>\n" +
		    		"<script src=\"http://" + host + "/friend/gadgets/script/OpensocialReference.js\" type=\"text/javascript\"></script>\n" +
		    		"<script src=\"http://" + host + "/friend/gadgets/script/hi5person.js\" type=\"text/javascript\"></script>\n" +
		    		"<script src=\"http://" + host + "/friend/gadgets/script/hi5container.js\" type=\"text/javascript\"></script>\n" +
		    		"<script src=\"http://" + host + "/friend/gadgets/script/hi5profile.js\" type=\"text/javascript\"></script>\n" +
		    		"<script type=\"text/javascript\">\n" +
		    		" sandbox = new Sandbox(); \n" +
		    		" sandbox.init('preview'); \n" +
		    		"</script>\n";
		    	// Inject Javascript here
		    	responseXml = responseXml.replaceFirst("(?s)(<Content[^>]+>.*<!\\[CDATA\\[)", jscode);	
		    }
			
		} catch (Exception e) {

		} finally {
			// release the HTTP Connection
			if (get != null) {
				get.releaseConnection();
			}
		}
		response.setContentType("text/xml");
		ServletOutputStream responseOutputStream = response.getOutputStream();
		responseOutputStream.print(responseXml);
		responseOutputStream.flush();
		responseOutputStream.close();

	}
}
